from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.models.uc.partner_token import PartnerToken
from app.schemas.uc.partner_token import PartnerTokenCreate, PartnerTokenUpdate
from sqlalchemy import select
from fastapi import HTTPException

async def create_partner_token(session: Session, partner_token: PartnerTokenCreate) -> PartnerToken:
    db_partner_token = PartnerToken(**partner_token.model_dump())
    session.add(db_partner_token)
    await session.commit()
    await session.refresh(db_partner_token)
    return db_partner_token

async def get_partner_token(session: Session, uid: int, partner: int) -> PartnerToken:
    db_partner_token = await session.execute(
        select(PartnerToken).where(PartnerToken.uid == uid, PartnerToken.partner == partner)
    )
    return db_partner_token.scalar_one_or_none()

async def get_partner_token_by_id(session: Session, id: int) -> PartnerToken:
    db_partner_token = await session.execute(
        select(PartnerToken).where(PartnerToken.id == id)
    )
    return db_partner_token.scalar_one_or_none()

async def update_partner_token(session: Session, uid: int, partner: int, partner_token: PartnerTokenUpdate) -> PartnerToken:
    db_partner_token = await get_partner_token(session=session, uid=uid, partner=partner)
    if not db_partner_token:
        raise HTTPException(status_code=404, detail="Partner token not found")
    for key, value in partner_token.model_dump(exclude_unset=True).items():
        setattr(db_partner_token, key, value)
    session.add(db_partner_token)
    await session.commit()
    await session.refresh(db_partner_token)
    return db_partner_token